package server.model.goodModel;

import com.alibaba.fastjson.JSON;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import server.db.DBDriver;
import server.db.DBFactory;
import server.entity.Code;
import server.entity.Good;
import server.model.factory.ModelFactory;
import server.util.DBUtils;
import server.util.InfoUtils.Info;
import server.util.InfoUtils.InfoEnum;
import server.util.InfoUtils.InfoUtil;
import server.util.MyUtils;

import java.util.ArrayList;
import java.util.List;

public class GoodModel {
    //添加商品
    public Info addGood(Good good) {
        Info info = null;
        if (!MyUtils.NOTNULL(good.getGoodName(), good.getPrice(), good.getCount())) {
            return InfoUtil.getInfo(InfoEnum.PARAMS_NULL);
        }
        String sql = "insert into good (good_name,pic,price,category,count,store_id,description,status) values (?,?,?,?,?,?,?,1)";
        ArrayList<Object> params = new ArrayList<>();
        params.add(good.getGoodName());
        params.add(good.getPic());
        params.add(good.getPrice());
        params.add(good.getCategory());
        params.add(good.getCount());
        params.add(good.getStoreId());
        params.add(good.getDescription());

        int line = DBFactory.getDBDriver().update(sql, params.toArray());
        if (line > 0) {
            Integer goodId = DBUtils.getInsertId("good_id");
            if (insertGood2Store(goodId, good.getStoreId())) {
                return InfoUtil.getInfo(InfoEnum.SUCCESS);
            }
        } else {
            info = InfoUtil.getInfo(InfoEnum.FAIL);
        }
        return info;
    }

    private boolean insertGood2Store(int goodId, int storeId) {
        String sql = "update store set good = json_array_append(good,'$',?) where store_id = ?";
        if (DBFactory.getDBDriver().update(sql, goodId, storeId) > 0) {
            return true;
        } else return false;
    }


    //删除商品
    public Info deleteGood(int goodId, int storeId) {
        Info info = null;
        String sql = "delete from good where good_id = ?";

        int line = DBFactory.getDBDriver().update(sql, goodId);

        if (line > 0) {
            if (deleteFromStore(goodId, storeId))
                return InfoUtil.getInfo(InfoEnum.SUCCESS);
        } else {
            info = InfoUtil.getInfo(InfoEnum.FAIL);
        }
        return info;
    }

    //在store数据表里删除商品
    private boolean deleteFromStore(Integer goodId, int storeId) {
        String getSql = "select good from store where store_id = " + storeId;
        String getGood = DBFactory.getDBDriver().queryOne(getSql);
        if (getGood == null) {
            return false;
        }
        List<Integer> goods = JSON.parseArray(getGood, Integer.class);
        goods.remove(goodId);
        String setGood = JSON.toJSONString(goods);
        String setSql = "update store set good = ? where store_id = ?";
        int line = DBFactory.getDBDriver().update(setSql, setGood, storeId);
        if (line > 0) {
            return true;
        } else {
            return false;
        }
    }


    //上架或下架
    public Info shelfDownOrUp(int goodId) {
        String sql = "update good set status = abs(status-1) where good_id = ?";
        int line = DBFactory.getDBDriver().update(sql, goodId);

        if (line > 0) {
            //获取更改后的status
            String getStatusSql = "select status from good where good_id = " + goodId;
            String nowStatus = DBFactory.getDBDriver().queryOne(getStatusSql);
            return InfoUtil.getInfo(nowStatus);
        } else {
            return InfoUtil.getInfo(InfoEnum.FAIL);
        }
    }

    //通过关键字查询商品
    public Info getGoodsByKey(String key, Integer page, Integer num) {
        int size = key.length();
        //将key转化为char数组
        char[] c = key.toCharArray();
        //sql语句
        StringBuilder sql = new StringBuilder("select good_id,good_name,pic,price,auction_id from good where good_name like '%");
        //将key拆分为"%a%b%c%"的形式
        for (int i = 0; i < size; i++) {
            sql.append(c[i]).append("%");
        }
        sql.append("'");

        Integer startId = (page - 1) * num;
        sql.append(" and status = 1 order by good_id desc " + " limit " + startId + "," + num);
        System.out.println(sql);
        List<Good> goods = DBFactory.getDBDriver().query(sql.toString(), new BeanListHandler<>(Good.class, DBDriver.getProcess()));
        Integer count = getCountByKey(key);
        if (goods == null || count == -1) {
            return InfoUtil.getInfo(InfoEnum.FAIL);
        } else if (goods.size() == 0) {
            return InfoUtil.getInfo(1, "没有找到你想要的商品呦");
        } else {
            page = count == 0 ? 0 : (count - 1) / num + 1;

            return InfoUtil.getInfo(0, page.toString(), goods);
        }
    }

    public Integer getCountByKey(String key) {
        int size = key.length();
        //将key转化为char数组
        char[] c = key.toCharArray();
        //sql语句
        StringBuilder sql = new StringBuilder("select count(good_id) from good where good_name like '%");
        //将key拆分为"%a%b%c%"的形式
        for (int i = 0; i < size; i++) {
            sql.append(c[i]).append("%");
        }
        sql.append("'").append(" and status = 1");
        String count = DBFactory.getDBDriver().queryOne(sql.toString());
        if (count == null) {
            return -1;
        }
        return Integer.parseInt(count);
    }

    public Info purchase(Integer userId, Integer goodId, Integer count) {
        Info info1, info2 = null;

        if (!MyUtils.NOTNULL(goodId, count)) {  //判断字段是否为空
            return InfoUtil.getInfo(InfoEnum.PARAMS_NULL);
        }

        //减少商品的数目
        Info decreaseInfo = ModelFactory.getGoodInfoModel().GoodNumDecrease(goodId, count);
        if (decreaseInfo.getCode() != 0) {
            return decreaseInfo;
        }

        Code code = new Code();
        code.setUserId(userId);
        code.setGold(-(Double) decreaseInfo.getData());
        //减少用户金币
        Info info = ModelFactory.getUserInfoModel().setGold(code);
        if (info.getCode() != 0) {
            if (info.getCode() == 2) {
                return info;
            }
            return InfoUtil.getInfo(InfoEnum.FAIL);
        }
        //设置买过的商品
        info1 = ModelFactory.getJsonIdInUserModel().addBought(userId, goodId);
        //增加购买记录
        info2 = ModelFactory.getRecordModel().setRecord(userId, goodId, count);
        if (info1.getCode() != 0 || info2.getCode() != 0) {
            return InfoUtil.getInfo(InfoEnum.FAIL);
        }
        return InfoUtil.getInfo(InfoEnum.SUCCESS);
    }

    public Info auctionPurchase(Integer userId, Integer goodId, Double gold) {
        Info info1, info2 = null;

        //减少商品的数目
        Info decreaseInfo = ModelFactory.getGoodInfoModel().GoodNumDecrease(goodId, 1);
        if (decreaseInfo.getCode() != 0) {
            return InfoUtil.getInfo(InfoEnum.FAIL);
        }

        Code code = new Code();
        code.setUserId(userId);
        code.setGold(-gold);
        //减少用户金币
        Info info = ModelFactory.getUserInfoModel().setGold(code);
        if (info.getCode() != 0) {
            return info;
        }
        //设置买过的商品
        info1 = ModelFactory.getJsonIdInUserModel().addBought(userId, goodId);
        //增加购买记录
        info2 = ModelFactory.getRecordModel().setRecord(userId, goodId, 1);
        if (info1.getCode() != 0 || info2.getCode() != 0) {
            return InfoUtil.getInfo(InfoEnum.FAIL);
        }
        return InfoUtil.getInfo(InfoEnum.SUCCESS);
    }
}
